#include "widget.h"
#include <string>
#include <iostream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //界面初始化操作
    this->setGeometry(0,0,800,480);

    this->tcpServe=new QTcpServer(this);
    this->tcpSocket=new QTcpSocket(this);

    this->button[0]=new QPushButton(QString("开始监听"));//开始监听
    this->button[1]=new QPushButton(QString("停止监听"));//停止监听
    this->button[2]=new QPushButton(QString("清空文本"));//清空聊天文本
    this->button[3]=new QPushButton(QString("发送消息"));//发送消息
    button[1]->setEnabled(false);

    this->hLayout[0]=new QHBoxLayout;
    this->hLayout[1]=new QHBoxLayout;
    this->hLayout[2]=new QHBoxLayout;
    this->hLayout[3]=new QHBoxLayout;

    hwidget[0]=new QWidget;
    hwidget[1]=new QWidget;
    hwidget[2]=new QWidget;

    vLayout=new QVBoxLayout;

    lineEdit=new QLineEdit(QString("abandon"));
    comboBox=new QComboBox;
    spinBox=new QSpinBox;
    browser=new QTextBrowser;

    label[0]=new QLabel(QString("监听IP地址"));
    label[1]=new QLabel(QString("监听端口"));

    //根据文字大小自适应大小
    label[0]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    label[1]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    //设置端口号范围
    spinBox->setRange(10000,99999);

    hLayout[0]->addWidget(button[0]);
    hLayout[0]->addWidget(button[1]);
    hLayout[0]->addWidget(button[2]);

    hwidget[0]->setLayout(hLayout[0]);

    hLayout[1]->addWidget(label[0]);
    hLayout[1]->addWidget(comboBox);
    hLayout[1]->addWidget(label[1]);
    hLayout[1]->addWidget(spinBox);
    hwidget[1]->setLayout(hLayout[1]);

    hLayout[2]->addWidget(lineEdit);
    hLayout[2]->addWidget(button[3]);
    hwidget[2]->setLayout(hLayout[2]);

    vLayout->addWidget(browser);
    vLayout->addWidget(hwidget[1]);
    vLayout->addWidget(hwidget[0]);
    vLayout->addWidget(hwidget[2]);

    this->setLayout(vLayout);

    getLocalHostIP();

    connectSigToSlots();

}

Widget::~Widget() {}

void Widget::getLocalHostIP()
{
    QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
    for(auto listNumber : interfaceList)
    {
        browser->append(QString("网卡设备："+listNumber.name()));
        browser->append(QString("MAC地址："+listNumber.hardwareAddress()));
        QList<QNetworkAddressEntry> entryList = listNumber.addressEntries();
        foreach (QNetworkAddressEntry entry, entryList)
        {
            if(entry.ip().protocol()==QAbstractSocket::IPv4Protocol)
            {
                comboBox->addItem(QString(entry.ip().toString()));
                ipList<<entry.ip();
            }
        }

    }
}

void Widget::connectSigToSlots()
{
    connect(button[0],&QPushButton::clicked,this,&Widget::startListen);
    connect(button[1],&QPushButton::clicked,this,&Widget::stopListen);
    connect(button[2],&QPushButton::clicked,this,&Widget::clearTextBrower);
    connect(button[3],&QPushButton::clicked,this,&Widget::sendMessage);
    connect(tcpServe,&QTcpServer::newConnection,this,&Widget::clientConnected);

}

void Widget::clientConnected()
{
    tcpSocket = tcpServe->nextPendingConnection();
    quint16 port = tcpSocket->peerPort();
    QString ip = tcpSocket->peerAddress().toString();
    browser->append(QString("客户端已连接"));
    browser->append(QString("IP地址：%1").arg(ip));
    browser->append(QString("客户端端口号：%1").arg(port));

    connect(tcpSocket,&QTcpSocket::readyRead,this,&Widget::receiveMessage);
    connect(tcpSocket,&QTcpSocket::stateChanged,this,&Widget::socketStateChanged);

}

void Widget::startListen()
{
    //判断当前主机是否有ip地址
    if(comboBox->currentIndex()!=-1)
    {
        qDebug()<<"开始监听";
        tcpServe->listen(ipList[comboBox->currentIndex()],spinBox->value());
    }
    button[0]->setEnabled(false);
    button[1]->setEnabled(true);
    comboBox->setEnabled(false);
    lineEdit->setEnabled(false);

    browser->append(QString("服务器IP地址："+comboBox->currentText()));
    browser->append(QString("端口号："+spinBox->text()));
}

void Widget::stopListen()
{
    qDebug()<<"停止监听";
    tcpServe->close();
    if(tcpSocket->state()==QAbstractSocket::ConnectedState)
    {
        tcpSocket->disconnectFromHost();
    }
    button[0]->setEnabled(true);
    button[1]->setEnabled(false);
    comboBox->setEnabled(true);
    lineEdit->setEnabled(true);

    browser->append(QString("已停止监听端口：%1").arg(spinBox->value()));

}

void Widget::clearTextBrower()
{
    browser->clear();
}

void Widget::receiveMessage()
{
    QString message=QString("客户端："+tcpSocket->readAll());
    browser->append(message);
}

void Widget::sendMessage()
{
    if(tcpSocket==nullptr)
    {
        return;
    }
    if(tcpSocket->state()==QAbstractSocket::ConnectedState)
    {
        tcpSocket->write(lineEdit->text().toUtf8().data());
        browser->append(QString("服务端："+lineEdit->text()));
    }
}

void Widget::socketStateChanged(QAbstractSocket::SocketState state)
{
    switch(state)
    {
    case QAbstractSocket::UnconnectedState:
        browser->append(QString("socket状态：%1").arg("UnconnectedState"));
        break;
    case QAbstractSocket::ConnectedState:
        browser->append(QString("socket状态：%1").arg("ConnectedState"));
        break;
    case QAbstractSocket::ConnectingState:
        browser->append(QString("socket状态：%1").arg("ConnectingState"));
        break;
    case QAbstractSocket::HostLookupState:
        browser->append(QString("socket状态：%1").arg("HostLookupState"));
        break;
    case QAbstractSocket::BoundState:
        browser->append(QString("socket状态：%1").arg("BoundState"));
        break;
    case QAbstractSocket::ListeningState:
        browser->append(QString("socket状态：%1").arg("ListeningState"));
        break;
    case QAbstractSocket::ClosingState:
        browser->append(QString("socket状态：%1").arg("ClosingState"));
        break;
    default:
        break;
    }
}
